from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import dbtools
import sys

class LeftWidget(QWidget):
    def __init__(self) -> None:
        super().__init__()
        self.btn0 = QPushButton("Home",self)
        self.btn1 = QPushButton("用户信息",self)
        self.setFixedWidth(134)
        self.init_ui()
        self.set_widget_style()
    def userInfo(self):
        for i in range(len(self.right)):
            self.right[i].close()
        self.right[1].show()
        self.right_layout.addWidget(self.right[1])
        self.btn0.setStyleSheet("color:rgb(170,170,170);border:none;")
        self.btn1.setStyleSheet("color:rgb(73,166,234);border:none;")
    def home(self):
        for i in range(len(self.right)):
            self.right[i].close()
        self.right[0].show()
        self.right_layout.addWidget(self.right[0])
        self.btn0.setStyleSheet("color:rgb(73,166,234);border:none;")
        self.btn1.setStyleSheet("color:rgb(170,170,170);border:none;")
    def get_widget_pointer(self,widget,layout):
        self.right = widget
        self.right_layout = layout
    def init_ui(self):
        pal = QPalette(self.palette())
        pal.setColor(QPalette.Background,QColor(255,255,255))
        self.setAutoFillBackground(True)
        self.setPalette(pal)
        self.btn0.move(15,40)
        self.btn1.move(15,130)
        self.btn0.clicked.connect(self.home)
        self.btn1.clicked.connect(self.userInfo)
    def set_widget_style(self):
        font = QFont("PingFang SC Regular")
        font.setPixelSize(20)
        self.btn0.setFont(font)
        self.btn1.setFont(font)
        self.btn0.setStyleSheet("color:rgb(73,166,234);border:none;")
        self.btn1.setStyleSheet("color:rgb(170,170,170);border:none;")
        
class TopWidget(QWidget):
    def __init__(self) -> None:
        super().__init__()
        pal = QPalette(self.palette())
        pal.setColor(QPalette.Background,QColor(255,255,255))
        self.setAutoFillBackground(True)
        self.setPalette(pal)
        #设置logo
        self.logo = QLabel(self)
        self.pix = QPixmap("static/cqu.jpg")
        self.pix = self.pix.scaled(39, 39, Qt.KeepAspectRatio)
        self.logo.setPixmap(QPixmap(self.pix))
        self.logo.move(5,0)
        #设置标题
        self.tittle = QLabel(self)
        self.tittle.setText("审核")
        font = QFont('PingFang SC Regular')
        font.setPixelSize(20)
        self.tittle.setFont(font)
        self.tittle.move(55,0)

        self.side = QLabel(self)
        self.pic = QPixmap("static/people.jpg")
        self.pic = self.pic.scaled(42, 33, Qt.KeepAspectRatio)
        self.side.setPixmap(QPixmap(self.pic))
        self.side.move(660,0)
        self.setFixedHeight(57)

class Test(QWidget):
    def __init__(self):
        super().__init__()
        self.setGeometry(350,250,754,460)
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)
        
        self.main_wid = QWidget()
        self.main_lay = QHBoxLayout()
        self.main_wid.setLayout(self.main_lay)
        self.left = LeftWidget()
        self.main_lay.addWidget(self.left)
        self.middle = [RightWidget(),UserInfo()]
        self.main_lay.addWidget(self.middle[0])
        self.top = TopWidget()
        self.layout.addWidget(self.top)
        self.layout.addWidget(self.main_wid)
        self.left.get_widget_pointer(self.middle,self.main_lay)

class RightWidget(QMainWindow):
    def __init__(self):
        super(QMainWindow, self).__init__()
        self.dbList = dbtools.listAll(0)
        self.__init_ui()
        
    def __init_ui(self):
        self.resize(500, 250)
        self.table_widget = TableWidget1()  # 实例化表格
        self.table_widget.setPageController(len(self.dbList)//10 + 1)  # 表格设置页码控制
        self.table_widget.control_signal.connect(self.page_controller)
        self.setCentralWidget(self.table_widget)


    def page_controller(self, signal):
        total_page = self.table_widget.showTotalPage()
        p = 0
        if "home" == signal[0]:
            self.table_widget.curPage.setText("1")
            p = 1
        elif "pre" == signal[0]:
            if 1 == int(signal[1]):
                QMessageBox.information(self, "提示", "已经是第一页了", QMessageBox.Yes)
                return
            self.table_widget.curPage.setText(str(int(signal[1]) - 1))
            p = int(signal[1]) - 1
        elif "next" == signal[0]:
            if total_page == int(signal[1]):
                QMessageBox.information(self, "提示", "已经是最后一页了", QMessageBox.Yes)
                return
            self.table_widget.curPage.setText(str(int(signal[1]) + 1))
            p = int(signal[1]) + 1
        elif "final" == signal[0]:
            self.table_widget.curPage.setText(str(total_page))
            p = int(total_page)
        elif "confirm" == signal[0]:
            if total_page < int(signal[1]) or int(signal[1]) <= 0:
                QMessageBox.information(self, "提示", "跳转页码超出范围", QMessageBox.Yes)
                return
            self.table_widget.curPage.setText(signal[1])
            p = int(signal[1])

        self.changeTableContent(p)  # 改变表格内容

    def changeTableContent(self, p):
        """根据当前页改变表格的内容"""
        self.table_widget.pageList(p)
        cur_page = self.table_widget.curPage.text()

class TableWidget1(QWidget):

    control_signal = pyqtSignal(list)

    def __init__(self, *args, **kwargs):
        super(TableWidget1, self).__init__(*args, **kwargs)
        self.__init_ui()

    def __init_ui(self):
        self.table = QTableWidget(10, 5) 
        self.table.setHorizontalHeaderLabels(['用户名','手机号','真实姓名','邮箱','操作'])
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 自适应宽度
        self.table.verticalHeader().setSectionResizeMode(QHeaderView.Stretch) #自适应高度
        self.table.verticalHeader().hide()
        self.lineEdit = QLineEdit()
        self.btn = QPushButton("搜索",self)
        self.btn.clicked.connect(self.search)
        #添加水平布局
        self.hbox = QHBoxLayout()
        self.hbox.addWidget(self.lineEdit)
        self.hbox.addWidget(self.btn)

        #添加垂直布局
        self.__layout = QVBoxLayout()
        self.__layout.addWidget(self.table)
        #添加布局
        vlayout = QVBoxLayout() 
        vlayout.addLayout(self.hbox)
        vlayout.addLayout(self.__layout)
        self.setLayout(vlayout)
        self.pageList(1)

    def search(self):
        truename = self.lineEdit.text()
        if (len(truename) == 0):
            self.pageList(1)
            return
        res = dbtools.search(truename)
        self.table.clearContents()
        if (res == []):
            return
        for i in range(4):
            temp_data = res[0][i]
            data=QTableWidgetItem(str(temp_data))
            self.table.setItem(0,i,data)
        self.table.setCellWidget(0, 4, self.buttonForRow(0, 4))
    # 列表内添加按钮
    def buttonForRow(self,id,p):
        widget=QWidget()
        
        # 通过审核
        acBtn = QPushButton('通过')
        acBtn.clicked.connect(lambda:self.ac(id,p))

        # 拒绝
        rjBtn = QPushButton('拒绝')

        rjBtn.clicked.connect(lambda:self.rj(id,p))

        hLayout = QHBoxLayout()
        hLayout.addWidget(acBtn)
        hLayout.addWidget(rjBtn)
        hLayout.setContentsMargins(5,2,5,2)
        widget.setLayout(hLayout)
        return widget
    
    def ac(self, id,p):
        username = self.table.item(id,0).text()
        dbtools.accept(str(username))
        self.pageList(p)

    def rj(self, id, p):
        username = self.table.item(id,0).text()
        dbtools.reject(str(username))
        self.pageList(p)

    def pageList(self, p):
        dbList = dbtools.listAll(0)
        self.table.clearContents()
        for i in range(10):
            temp = (p - 1) * 10 + i
            if (temp < len(dbList)):
                for j in range(5):
                    if (j < 4) :
                        temp_data=dbList[temp][j]  #临时记录，不能直接插入表格
                        data=QTableWidgetItem(str(temp_data)) #转换后可插入表格
                        self.table.setItem(i,j,data)
                    else :
                        self.table.setCellWidget(i, j, self.buttonForRow(i, p))

    def setPageController(self, page):
        """自定义页码控制器"""
        control_layout = QHBoxLayout()
        homePage = QPushButton("首页")
        prePage = QPushButton("<上一页")
        self.curPage = QLabel("1")
        nextPage = QPushButton("下一页>")
        finalPage = QPushButton("尾页")
        self.totalPage = QLabel("共" + str(page) + "页")
        skipLable_0 = QLabel("跳到")
        self.skipPage = QLineEdit()
        skipLabel_1 = QLabel("页")
        confirmSkip = QPushButton("确定")
        homePage.clicked.connect(self.__home_page)
        prePage.clicked.connect(self.__pre_page)
        nextPage.clicked.connect(self.__next_page)
        finalPage.clicked.connect(self.__final_page)
        confirmSkip.clicked.connect(self.__confirm_skip)
        control_layout.addStretch(1)
        control_layout.addWidget(homePage)
        control_layout.addWidget(prePage)
        control_layout.addWidget(self.curPage)
        control_layout.addWidget(nextPage)
        control_layout.addWidget(finalPage)
        control_layout.addWidget(self.totalPage)
        control_layout.addWidget(skipLable_0)
        control_layout.addWidget(self.skipPage)
        control_layout.addWidget(skipLabel_1)
        control_layout.addWidget(confirmSkip)
        control_layout.addStretch(1)
        self.__layout.addLayout(control_layout)

    def __home_page(self):
        """点击首页信号"""
        self.control_signal.emit(["home", self.curPage.text()])

    def __pre_page(self):
        """点击上一页信号"""
        self.control_signal.emit(["pre", self.curPage.text()])

    def __next_page(self):
        """点击下一页信号"""
        self.control_signal.emit(["next", self.curPage.text()])

    def __final_page(self):
        """尾页点击信号"""
        self.control_signal.emit(["final", self.curPage.text()])

    def __confirm_skip(self):
        """跳转页码确定"""
        self.control_signal.emit(["confirm", self.skipPage.text()])

    def showTotalPage(self):
        """返回当前总页数"""
        return int(self.totalPage.text()[1:-1])

class TableWidget(QWidget):
    control_signal = pyqtSignal(list)

    def __init__(self, *args, **kwargs):
        super(TableWidget, self).__init__(*args, **kwargs)
        self.__init_ui()

    def __init_ui(self):

        self.table = QTableWidget(10, 4) 
        self.table.setHorizontalHeaderLabels(['用户名','手机号','真实姓名','邮箱'])
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 自适应宽度
        self.table.verticalHeader().setSectionResizeMode(QHeaderView.Stretch) #自适应高度
        self.table.verticalHeader().hide()
        self.btn = QPushButton("搜索",self)
        self.btn.clicked.connect(self.search)
        self.lineEdit = QLineEdit()
        #添加水平布局
        self.hbox = QHBoxLayout()
        self.hbox.addWidget(self.lineEdit)
        self.hbox.addWidget(self.btn)
        #添加垂直布局
        self.__layout = QVBoxLayout()
        self.__layout.addWidget(self.table)
        #添加布局
        vlayout = QVBoxLayout() 
        vlayout.addLayout(self.hbox)
        vlayout.addLayout(self.__layout)
        self.setLayout(vlayout)
        self.pageList(1)

    def search(self):
        truename = self.lineEdit.text()
        if (len(truename) == 0):
            self.pageList(1)
            return
        res = dbtools.search(truename)
        self.table.clearContents()
        if (res == []):
            return
        for i in range(4):
            temp_data = res[0][i]
            data=QTableWidgetItem(str(temp_data))
            self.table.setItem(0,i,data)

    def pageList(self, p):
        dbList = dbtools.listAll(1)
        self.table.clearContents()
        for i in range(10):
            temp = (p - 1) * 10 + i
            if (temp < len(dbList)):
                for j in range(5):
                    if (j < 4) :
                        temp_data=dbList[temp][j]  #临时记录，不能直接插入表格
                        data=QTableWidgetItem(str(temp_data)) #转换后可插入表格
                        self.table.setItem(i,j,data)

    def setPageController(self, page):
        """自定义页码控制器"""
        control_layout = QHBoxLayout()
        homePage = QPushButton("首页")
        prePage = QPushButton("<上一页")
        self.curPage = QLabel("1")
        nextPage = QPushButton("下一页>")
        finalPage = QPushButton("尾页")
        self.totalPage = QLabel("共" + str(page) + "页")
        skipLable_0 = QLabel("跳到")
        self.skipPage = QLineEdit()
        skipLabel_1 = QLabel("页")
        confirmSkip = QPushButton("确定")
        homePage.clicked.connect(self.__home_page)
        prePage.clicked.connect(self.__pre_page)
        nextPage.clicked.connect(self.__next_page)
        finalPage.clicked.connect(self.__final_page)
        confirmSkip.clicked.connect(self.__confirm_skip)
        control_layout.addStretch(1)
        control_layout.addWidget(homePage)
        control_layout.addWidget(prePage)
        control_layout.addWidget(self.curPage)
        control_layout.addWidget(nextPage)
        control_layout.addWidget(finalPage)
        control_layout.addWidget(self.totalPage)
        control_layout.addWidget(skipLable_0)
        control_layout.addWidget(self.skipPage)
        control_layout.addWidget(skipLabel_1)
        control_layout.addWidget(confirmSkip)
        control_layout.addStretch(1)
        self.__layout.addLayout(control_layout)

    def __home_page(self):
        """点击首页信号"""
        self.control_signal.emit(["home", self.curPage.text()])

    def __pre_page(self):
        """点击上一页信号"""
        self.control_signal.emit(["pre", self.curPage.text()])

    def __next_page(self):
        """点击下一页信号"""
        self.control_signal.emit(["next", self.curPage.text()])

    def __final_page(self):
        """尾页点击信号"""
        self.control_signal.emit(["final", self.curPage.text()])

    def __confirm_skip(self):
        """跳转页码确定"""
        self.control_signal.emit(["confirm", self.skipPage.text()])

    def showTotalPage(self):
        """返回当前总页数"""
        return int(self.totalPage.text()[1:-1])

class UserInfo(QMainWindow):
    def __init__(self):
        super(QMainWindow, self).__init__()
        self.dbList = dbtools.listAll(1)
        self.__init_ui()

    def __init_ui(self):
        self.resize(500, 250)
        self.table_widget = TableWidget()  # 实例化表格
        self.table_widget.setPageController(len(self.dbList)//10 + 1)  # 表格设置页码控制
        self.table_widget.control_signal.connect(self.page_controller)
        self.setCentralWidget(self.table_widget)

    def page_controller(self, signal):
        total_page = self.table_widget.showTotalPage()
        p = 0
        if "home" == signal[0]:
            self.table_widget.curPage.setText("1")
            p = 1
        elif "pre" == signal[0]:
            if 1 == int(signal[1]):
                QMessageBox.information(self, "提示", "已经是第一页了", QMessageBox.Yes)
                return
            self.table_widget.curPage.setText(str(int(signal[1]) - 1))
            p = int(signal[1]) - 1
        elif "next" == signal[0]:
            if total_page == int(signal[1]):
                QMessageBox.information(self, "提示", "已经是最后一页了", QMessageBox.Yes)
                return
            self.table_widget.curPage.setText(str(int(signal[1]) + 1))
            p = int(signal[1]) + 1
        elif "final" == signal[0]:
            self.table_widget.curPage.setText(str(total_page))
            p = int(total_page)
        elif "confirm" == signal[0]:
            if total_page < int(signal[1]) or int(signal[1]) <= 0:
                QMessageBox.information(self, "提示", "跳转页码超出范围", QMessageBox.Yes)
                return
            self.table_widget.curPage.setText(signal[1])
            p = int(signal[1])

        self.changeTableContent(p)  # 改变表格内容

    def changeTableContent(self, p):
        """根据当前页改变表格的内容"""
        self.table_widget.pageList(p)
        cur_page = self.table_widget.curPage.text()

if __name__=="__main__":
    app = QApplication(sys.argv)
    window = Test()
    window.show()
    sys.exit(app.exec_())